package com.csk.zsk.compents.dao.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.hibernate.Query;
import org.hibernate.criterion.Criterion;
import org.springframework.stereotype.Repository;

import com.csk.zsk.commons.dao.impl.BaseHibernateDao;
import com.csk.zsk.commons.orm.Page;
import com.csk.zsk.commons.orm.PropertyFilter;
import com.csk.zsk.commons.orm.PropertyFilter.MatchType;
import com.csk.zsk.compents.dao.BookDao;
import com.csk.zsk.compents.entity.Book;

@Repository
public class BookDaoImpl extends BaseHibernateDao<Book, String> implements BookDao {

	@Override
	public List<Book> searchTop10ByOrder(String startIndex) {
		return this.createQuery("from Book book where book.ordernum>=? order by book.ordernum", Integer.parseInt(startIndex)).setMaxResults(10).list();
	}

	@Override
	public List<Book> searchTop10ByRec(String startIndex) {
		return this.createQuery("from Book book where book.recnum>=? order by book.recnum", Integer.parseInt(startIndex)).setMaxResults(10).list();
	}

	@Override
	public List<Book> searchTop10ByRandom() {
		String sql = "from Book book where book.ordernum in (:ids)";


		String rlt = createSQLQuery("select count(*) from Book").uniqueResult().toString();
		List<Integer> strs = getRandomNum(Integer.parseInt(rlt),10);
		Query query = getSession().createQuery(sql);
		if (strs != null && strs.size() > 0) {
			return query.setParameterList("ids", strs).list();
		} else {
			return null;
		}
	}
	
	private List<Integer> getRandomNum(int maxnum,int length){
		List<Integer> strs = new ArrayList<Integer>();
		
		Random random=new Random(); 
		for(int i=0;i<length;i++){
			strs.add(new Integer(random.nextInt(maxnum)+1)) ;
		}
		return strs;
	}
	

}
